const { ccclass, property } = cc._decorator;

@ccclass
export default class airstrip extends cc.Component {
    @property(cc.Vec2)
    interval: cc.Vec2 = null;//间隔时间区间
    @property(cc.Vec2)
    speed: cc.Vec2 = null;//发射速度区间
    @property
    faceTo: number = 0;//发射方向 0：随机
    @property
    isAnim: boolean = false;//是否需要播放动画
    @property
    scaleTo: number = 1;//缩放

    distance: number = 0;//飞行距离
    _anim: cc.Animation = null;
    _faceTo: number = 0;
    _LastDt: number = 0;
    _interval: number = 0;
    _speed: number = 0;
    _isFly: boolean = false;
    _isNext: boolean = false;

    onLoad() {
        this.node.scale = this.scaleTo;
        this._anim = this.node.getComponent(cc.Animation);
        this.distance = this.node.parent.width / 2;
        this.node.x = this.distance + 500;
        this.Next();
    }

    private Next() {
        this._LastDt = 0;
        this._interval = Math.floor((Math.random() * (this.interval.y - this.interval.x))) + this.interval.y;
        this._speed = Math.floor((Math.random() * (this.speed.y - this.speed.x))) + this.speed.y;
        if (this.faceTo == 0) {
            let rand = Math.random();
            if (rand > 0.5) {
                this._faceTo = 1;
            }
            else {
                this._faceTo = -1;
            }
        }
        else {
            this._faceTo = this.faceTo;
        }
        this._isNext = true;
        this._isFly = false;
    }
    private _start() {
        this._LastDt = 0;
        this.node.anchorX = 0;
        this.node.scaleX = this._faceTo * this.scaleTo;
        this.node.x = this.distance * -1 * this._faceTo;
        this.node.y = 0 - Math.floor((Math.random() * this.node.parent.height));
        if (this._anim)
            this._anim.play("anim");
        this._isFly = true;
    }
    private _stop() {
        this._isFly = false;
        this._isNext = false;
        if (this._anim)
            this._anim.stop("anim");
    }
    private fly(dt: number) {
        this.node.x += this._speed * this._faceTo * dt;
        if (Math.abs(this.node.x) > this.distance + this.node.width) {
            this._stop();
        }
    }

    update(dt: number) {
        if (this._isFly) {
            this.fly(dt);
        }
        else {
            this._LastDt += dt;
            if (!this._isNext) {
                this.Next();
            }
            else if (this._LastDt >= this._interval) {
                this._start();
            }
        }
    }
}
